<?php
namespace app\api\controller\wdsxh;
use addons\wdsxh\library\Wxapp;
use app\admin\model\wdsxh\UserBelong;
use app\admin\model\User as Model;
use app\admin\model\wdsxh\Member;
use app\admin\model\wdsxh\MemberUnitLevel;
class User extends Base
{
    protected $noNeedLogin = ['login','is_auth'];
    protected $noNeedRight = '*';
    /*
     * 微信用户登录
     */
    public function login(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $code=$this->request->param('code');
        $param = $this->request->param();
        if(empty($code)){
            $this->error('code参数错误');
        }
        $data=Wxapp::wxlogin($code);
        if(empty($data['openid'])){
            $this->error('小程序登录失败',$data);
        }
        $openid=$data['openid'];
        $userBelongObj = (new UserBelong())->where('openid',$openid)->find();
        if(!$userBelongObj){
            $user=Model::create(array(
                'group_id'=>1,
                'status'=>'normal',
                'joinip'=>request()->ip(),
                'jointime'=>time(),
                // 'unionid'=>$data['unionid'],
                'avatar'=>isset($param['avatar']) ? $param['avatar'] : '',
                'nickname'=>isset($param['nickname']) ? $param['nickname'] : '',
            ),true);
            $userBelongObj = UserBelong::create(array(
                'user_id' =>$user->id,
                'openid'=>$openid,
                'session_key'=>$data['session_key'],
            ));
        } else {
            $user = (new \app\admin\model\User())->get($userBelongObj['user_id']);
            $user->save();
        }
        if(!empty($data['unionid'])){
            $userBelongObj->unionid=$data['unionid'];
        }
        $userBelongObj->session_key=$data['session_key'];
        $userBelongObj->save();
        $this->auth->direct($user->id);
        $this->success($this->auth->getUserinfo());
    }

    /*
     * 用户是否授权成功
     */
    public function is_auth()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $code=$this->request->param('code');
        if(empty($code)){
            $this->error('code参数错误');
        }
        $data=Wxapp::wxlogin($code);
        if(empty($data['openid'])){
            $this->error('小程序登录失败',$data);
        }
        $openid=$data['openid'];
        $userBelongObj = (new UserBelong())->where('openid',$openid)->find();

        $auth_status = !empty($userBelongObj) ? 1 : 0;
        $this->success('请求成功！',['auth_status'=>$auth_status]);
    }


    /*
     * 获取用户信息
     */
    public function index(){
        $user=$this->auth->getUserinfo();
        if($user){
            $member=Member::where('uid',$this->auth->id)->order('id desc')->field('id,level_id,name,mobile,picture,society_post,company_post,images,introduction,jointime,expiretime')->find();
            $level=null;
            if($member){
                $member->picture=wdsxh_full_url($member->picture);
                $member->images=wdsxh_full_url($member->images,1);
                $level=MemberUnitLevel::where('id',$member->level_id)->field('id,name')->find();
            }
            $user['member']=$member;
            $user['level']=$level;
            $user['avatar'] = wdsxh_full_url($user['avatar']);
        }
        $this->success($user);
    }

    public function update(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $params=$this->request->param();
        $model=new \app\admin\model\User();
        $user=$model->get($this->auth->id);
        if(!$user){
            $this->error('用户信息不存在');
        }
        $user['nickname']=empty($params['nickname'])?$user['nickname']:$params['nickname'];
        $user['avatar']=empty($params['avatar'])?$user['avatar']:$params['avatar'];
        $user['mobile']=empty($params['mobile'])?$user['mobile']:$params['mobile'];
        $user->save();
        $pwd= empty($params['pwd'])?null:$params["pwd"];
        if(!empty($pwd)){
            if(strlen($pwd) < 6){
                $this->error('密码长度不能小于6个字符');
            }
            $this->auth->direct($user->id);
            $ret = $this->auth->changepwd($pwd, '', true);
            if (!$ret) {
                $this->error($this->auth->getError());
            }
        }
        // 合并后台添加的账号
        if(!empty($params['mobile'])) {
            $old_user = $model->get(['mobile' => $params['mobile'],'id' => ['<>',$user->id],'status' => 'normal','group_id' => 0]);
            if($old_user) {
                // 修改绑定会员
                model('app\admin\model\wdsxh\Member')->where(['uid' => $old_user->id,'status' => '1'])->update(['uid' => $user->id]);
                // 修改绑定会员的入会申请信息
                model('app\admin\model\wdsxh\MemberProfile')->where(['uid' => $old_user->id,'status' => '1'])->update(['uid' => $user->id]);
                // 删除后台添加的会员
                $old_user->delete();
            }
        }
        $user=$model->get($this->auth->id);
        $this->success('更新成功！',$user);
    }

    public function getPhone(){
        $code=$this->request->param('code');
        $iv=$this->request->param('iv');
        $encryptedData=$this->request->param('encryptedData','','trim');
        if(empty($code)){
            $this->error('code 参数错误');
        }
        if(empty($iv)){
            $this->error('iv 参数错误');
        }
        if(empty($encryptedData)){
            $this->error('encryptedData 参数错误');
        }
        $data=Wxapp::phone($code,$iv,$encryptedData);
        $this->success($data);
    }

    public function edit_user(){
        if (!$this->request->isPost()){
            $this->error('请求类型错误');
        }
        $params = $this->request->param();
        $model = new \app\admin\model\User();
        $user = $model->get($this->auth->id);
        if (!$user){
            $this->error('用户信息不存在');
        }
        $user['nickname']=empty($params['nickname'])?$user['nickname']:$params['nickname'];
        $user['avatar']=empty($params['avatar'])?$user['avatar']:$params['avatar'];
        $user->save();
        $this->success('更新成功！',$this->auth->getUserinfo());
    }
}